<template>
  <lay-container fluid="true" class="option-box">
    <lay-card>
      <lay-form style="margin-top: 10px">
        <lay-row>
          <lay-col :md="5">
            <lay-form-item label="操作人员" label-width="80">
              <lay-input
                v-model="searchQuery.operName"
                placeholder="请输入"
                size="sm"
                :allow-clear="true"
                style="width: 98%"
              ></lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="5">
            <lay-form-item label="模块标题" label-width="80">
              <lay-input
                v-model="searchQuery.title"
                placeholder="请输入"
                size="sm"
                :allow-clear="true"
                style="width: 98%"
              ></lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="8">
            <lay-form-item label="操作时间" label-width="80">
              <lay-date-picker
                size="sm"
                v-model="searchQuery.rangeTime"
                range
                type="datetime"
                :placeholder="['开始日期', '结束日期']"
              ></lay-date-picker
            ></lay-form-item>
          </lay-col>
          <lay-col :md="5">
            <lay-form-item label-width="20">
              <lay-button
                style="margin-left: 20px"
                type="normal"
                size="sm"
                @click="toSearch"
              >
                查询
              </lay-button>
              <lay-button size="sm" @click="toReset"> 重置 </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>
    <!-- table -->
    <div class="table-box">
      <lay-table
        :page="page"
        :height="'100%'"
        :columns="columns"
        :loading="loading"
        :default-toolbar="true"
        :data-source="dataSource"
        v-model:selected-keys="selectedKeys"
        @change="change"
        @sortChange="sortChange"
      >
        <template #operUrl="{ row }">
          <lay-tooltip
            :visible="false"
            trigger="hover"
            :content="row.operUrl"
          >
            <div class="oneRow">{{ row.operUrl }}</div>
          </lay-tooltip>
        </template>

        <template #status="{ row }">
          <div v-show="row.status == 0">
            <lay-tag color="#2dc570" variant="light">正常</lay-tag>
          </div>
          <div v-show="row.status == 1">
            <lay-tag color="#F5319D" variant="light">异常</lay-tag>
          </div>
        </template>
        <template #businessType="{ row }">
          <div class="oneRow">{{ getBusinessTypeText(row.businessType) }}</div>
        </template>
        <template #costTime="{ row }">
          <div class="oneRow">{{ row.costTime }}ms</div>
        </template>
        <template v-slot:toolbar> </template>
        <template v-slot:operator="{ row }">
          <lay-button
            size="xs"
            border="green"
            border-style="dashed"
            @click="showDetail(row)"
            >详情</lay-button
          >
        </template>
      </lay-table>
    </div>

    <!-- layer -->

    <lay-layer v-model="visible11" title="详情" :area="['700px', '500px']">
      <div style="padding: 20px">
        <lay-row>
          <lay-col md="4" class="title">操作人员</lay-col>
          <lay-col md="8" class="content">{{ dataLayer.operName }}</lay-col>
          <lay-col md="4" class="title">部门名称</lay-col>
          <lay-col md="8" class="content borderR">{{ dataLayer.deptName }}</lay-col>
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title">模块标题</lay-col>
          <lay-col md="8" class="content">{{ dataLayer.title }}</lay-col>
          <lay-col md="4" class="title">业务类型</lay-col>
          <lay-col md="8" class="content borderR">{{ getBusinessTypeText(dataLayer.businessType) }}</lay-col>
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title">操作时间</lay-col>
          <lay-col md="8" class="content">{{ dataLayer.operTime }}</lay-col>
          <lay-col md="4" class="title">请求耗时</lay-col>
          <lay-col md="8" class="content borderR"
            >{{ dataLayer.costTime }}ms</lay-col
          >
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title">请求方式</lay-col>
          <lay-col md="8" class="content">{{
            dataLayer.requestMethod
          }}</lay-col>
          <lay-col md="4" class="title">操作状态</lay-col>
          <lay-col md="8" class="content borderR">
            <div v-show="dataLayer.status == 0">
              <lay-tag color="#2dc570" variant="light">正常</lay-tag>
            </div>
            <div v-show="dataLayer.status == 1">
              <lay-tag color="#F5319D" variant="light">异常</lay-tag>
            </div>
          </lay-col>
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title">请求地址</lay-col>
          <lay-col md="20" class="content borderR">{{
            dataLayer.operUrl
          }}</lay-col>
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title">调用方法</lay-col>
          <lay-col md="20" class="content borderR">{{ dataLayer.method }}</lay-col>
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title">请求参数</lay-col>
          <lay-col md="20" class="content borderR">{{ dataLayer.operParam }}</lay-col>
        </lay-row>
        <lay-row>
          <lay-col md="4" class="title borderB">返回结果</lay-col>
          <lay-col md="20" class="content borderR borderB">{{ dataLayer.jsonResult }}</lay-col>
        </lay-row>
        <lay-row v-if="dataLayer.errorMsg">
          <lay-col md="4" class="title borderB">错误消息</lay-col>
          <lay-col md="20" class="content borderR borderB">{{ dataLayer.errorMsg }}</lay-col>
        </lay-row>
      </div>
    </lay-layer>
  </lay-container>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import { queryLimit, queryOne } from '../../../api/module/oper-log'

const searchQuery = ref({
  operName: '',
  title: '',
  rangeTime: []
})

function toReset() {
  searchQuery.value = {
    operName: '',
    title: '',
    rangeTime: []
  }
  toSearch()
}

function toSearch() {
  page.current = 1
  change(page)
}

const loading = ref(false)
const selectedKeys = ref([])
const page = reactive({ current: 1, limit: 10, total: 0 })
const columns = ref([
  { title: '操作人员', key: 'operName', sort: 'desc' },
  { title: '部门名称', key: 'deptName', sort: 'desc' },
  { title: '模块标题', key: 'title', sort: 'desc' },
  { title: '业务类型', width: '120px', key: 'businessType', sort: 'desc' },
  {
    title: '请求地址',
    width: '180px',
    key: 'operUrl',
    sort: 'desc',
    customSlot: 'operUrl'
  },
  { title: '请求方式', key: 'requestMethod' },
  {
    title: '状态',
    width: '100px',
    key: 'status',
    customSlot: 'status'
  },
  { title: '耗时', key: 'costTime', customSlot: 'costTime' },
  { title: '操作时间', width: '180px', key: 'operTime' },
  {
    title: '操作',
    width: '100px',
    customSlot: 'operator',
    key: 'operator',
    fixed: 'right'
  }
])
const change = async (page: any) => {
  loading.value = true
  try {
    let queryWhere = {
      pageIndex: page.current,
      pageSize: page.limit,
      needOrderBy: true, // 自定义排序开启
      orderByMethod: 2, // 2-倒序
      orderByKeyName: 'oper_time', // 排序字段
      selectByTimeKeyName: 'oper_time', // s排序字段
      requestBody: {
        operName: searchQuery.value.operName,
        title: searchQuery.value.title
      }
    }
    
    // 添加时间范围查询条件
    if (searchQuery.value.rangeTime && searchQuery.value.rangeTime.length === 2) {
      queryWhere.beginTime = searchQuery.value.rangeTime[0]
      queryWhere.endTime = searchQuery.value.rangeTime[1]
    }
    
    const response = await queryLimit(queryWhere)
    if (response.code === 200) {
      console.log('查询到的数据详情:', response.data)
      console.log('数据条数:', response.data.responseBody?.length || 0)
      console.log('总条数:', response.data.totalNum || 0)
      console.log('当前页码:', page.current)
      
      // 根据接口返回结构，数据在 response.data.responseBody 中
      dataSource.value = response.data.responseBody || []
      page.total = response.data.totalNum || 0
      
      console.log('渲染到表格的数据条数:', dataSource.value.length)
    } else {
      layer.msg(response.message || '查询失败')
    }
  } catch (error) {
    layer.msg('请求失败，请检查网络连接')
    console.error('查询操作日志失败:', error)
  } finally {
    loading.value = false
  }
}

const sortChange = (key: any, sort: number) => {
  layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}

const dataSource = ref([])

// 业务类型转换
const getBusinessTypeText = (type: number) => {
  const businessTypeMap = {
    0: '其它',
    1: '新增',
    2: '修改',
    3: '删除'
  }
  return businessTypeMap[type] || '未知'
}

const dataLayer = ref({
  operId: '',
  operName: '',
  deptName: '',
  title: '',
  businessType: 0,
  operUrl: '',
  requestMethod: '',
  status: 0,
  costTime: 0,
  operTime: '',
  method: '',
  operParam: '',
  jsonResult: '',
  errorMsg: ''
})

const visible11 = ref(false)

async function showDetail(row: any) {
  try {
    const response = await queryOne(row.operId)
    if (response.code === 200) {
      dataLayer.value = response.data
      visible11.value = true
    } else {
      layer.msg(response.message || '获取详情失败')
    }
  } catch (error) {
    layer.msg('获取详情失败，请检查网络连接')
    console.error('获取操作日志详情失败:', error)
  }
}

// 页面加载时初始化数据
onMounted(() => {
  change(page)
})
</script>

<style scoped>
.option-box {
  width: calc(100vw - 220px);
  height: calc(100vh - 110px);
  margin-top: 10px;
  box-sizing: border-box;
  overflow: hidden;
}
.top-search {
  margin-top: 10px;
  padding: 10px;
  height: 40px;
  border-radius: 4px;
  background-color: #fff;
}
.table-box {
  margin-top: 10px;
  padding: 10px;
  height: 700px;
  width: 100%;
  border-radius: 4px;
  box-sizing: border-box;
  background-color: #fff;
}

.search-input {
  display: inline-block;
  width: 98%;
  margin-right: 10px;
}
.table-style {
  margin-top: 10px;
}
.isChecked {
  display: inline-block;
  background-color: #e8f1ff;
  color: red;
}
.oneRow {
  width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
.title {
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
  display: inline-block;
  background: #f7f7f7;
  border-top: 1px solid #e8e8e8;
  border-left: 1px solid #e8e8e8;
}
.content {
  height: 40px;
  line-height: 40px;
  padding: 0 3px 0 10px;
  border-top: 1px solid #e8e8e8;
  border-left: 1px solid #e8e8e8;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
.borderR {
  border-right: 1px solid #e8e8e8;
}
.borderB {
  border-bottom: 1px solid #e8e8e8;
}
</style>